<template>
  <div>
    <Sticky v-if="test.id" :class-name="'sticky'">
      <el-row :gutter="24">
        <el-col :span="6">
          <span class="testItem testName testTitleLabel">
            试卷:
            <el-tooltip effect="dark" :content="test.title" placement="bottom">
              <router-link :to="{
                  path: '/testInfo',
                  query: {
                    id: test.id,
                  },
                }" class="testItemContent testTitleContent">{{ test.title }}</router-link>
            </el-tooltip>
          </span>
        </el-col>
        <el-col :span="18" class="testTitleCol">
          <span class="testItem">
            <template v-if="question.id">
              <el-button v-if="!question.readonly && !isEdit" size="mini" type="primary"
                @click="isEdit = true">编辑</el-button>
              <span v-if="!question.readonly && !isEdit" style="margin-left: 8px">
                <el-button v-if="!question.readonly && !isEdit" size="mini" type="info"
                  @click="saveQuestion(true)">继续添加</el-button>
              </span>
            </template>
            <el-button v-if="question.id && question.readonly" size="mini" type="primary"
              @click="bindQuestion()">关联题目</el-button>
          </span>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="10" class="testTitleCol">
          <span class="testItem testStructure">
            题目所属大题:
            <el-select :disabled="readonly" v-model="test.testStructure" size="mini" class="testItemContent">
              <el-option v-for="testStructureItem in test.testStructures" :key="testStructureItem.id"
                :label="testStructureItem.title" :value="testStructureItem.id" />
            </el-select>
          </span>
          <span class="testItem testScore">
            题目分值:
            <el-input-number :disabled="readonly" v-model="question.score" :controls="false" :min="1"
              class="testItemContent" size="mini" />
          </span>
          <span style="line-height: 35px">
            <template v-if="isShowTestUpOrDown()">
              <el-button :disabled="testUpDisabled" size="mini" icon="el-icon-arrow-up" circle
                @click="testQuestionUp" />
              <el-button :disabled="testDownDisabled" size="mini" icon="el-icon-arrow-down" circle
                @click="testQuestionDown" />
            </template>
          </span>
        </el-col>
      </el-row>
    </Sticky>
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card v-if="parentQuestion.id" class="box-card">
          <div slot="header" class="clearfix">
            <span>
              主题目
              <el-tag effect="dark" size="mini">{{
                parentQuestion.name
                ? parentQuestion.name
                : questionType[parentQuestion.type]
                }}</el-tag>
            </span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="goBack()">返回主题目</el-button>
          </div>
          <div style="width: 90%; margin-left: 5%; margin-top: 5px">
            <katex :katex-content="parentQuestion.title" index="parentQuestionTitle" />
          </div>
          <div style="width: 90%; margin-left: 5%; margin-top: 5px">
            <katex :katex-content="parentQuestion.materials" index="parentQuestionMaterials" />
          </div>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-row v-if="question.id && !test.id" :gutter="20" class="cardHeader" style="display: flex">
              <el-col style="flex: 1" />
              <el-col v-if="question.id && !test.id" class="cardHeader" style="width: 250px; margin-top: 4px">
                <el-button :disabled="questionUpDisabled" size="mini" class="flbtn" icon="el-icon-arrow-up" circle
                  @click="questionUp" />
                <el-button :disabled="questionDownDisabled" size="mini" class="flbtn" icon="el-icon-arrow-down" circle
                  @click="questionDown" />
              </el-col>
            </el-row>
            <el-row v-if="!question.readonly && !isEdit" :gutter="20" class="cardHeader" style="display: flex">
              <el-col style="flex: 1" />
              <el-col v-if="question.id && !test.id" class="cardHeader" style="width: 250px; margin-top: 4px">
                <el-button class="flbtn" size="small" type="primary" @click="isEdit = true">编辑</el-button>
              </el-col>
            </el-row>
          </div>
          <div class="content">
            <el-form ref="question" :rules="rules" :model="question" label-width="100px">
              <el-form-item label="科目" prop="subjectId">
                <el-cascader :disabled="readonly" v-model="question.subjectId" :options="subjectOptions"
                  @change="queryPoint">
                </el-cascader>
              </el-form-item>

              <el-form-item label="题目" prop="title" v-if="question.type != 6">
                <myEdit :disabled="readonly" v-model="question.title" />
              </el-form-item>

              <el-form-item label="材料" v-if="question.type == 6" prop="materials">
                <myEdit :disabled="readonly" v-model="question.materials" placeholder="如果存在材料,需填写材料" />
              </el-form-item>
              <el-form-item label="题目类型">
                <el-select :disabled="readonly" v-model="question.type" size="mini" placeholder="请选择题目类型"
                  @change="changeQuestionType">
                  <el-option v-for="(key, value) in questionType" :key="key" :label="key" :value="value" />
                </el-select>
              </el-form-item>
              <el-form-item label="题目类型别名">
                <el-input :disabled="readonly" v-model="question.alias" :placeholder="typeName" size="mini" />
              </el-form-item>
              <el-form-item label="  题目分值">
                <el-input-number :disabled="readonly" :min="1" v-model="question.score" />
              </el-form-item>
              <template>
                <el-form-item label="是否真题">
                  <el-switch :disabled="readonly" v-model="question.isOfficialQuestion" :active-value="1"
                    :inactive-value="0" />
                </el-form-item>
                <el-form-item v-if="question.isOfficialQuestion" label="真题出处">
                  <el-input :disabled="readonly" v-model="question.officialQuestionSource" placeholder="真题名称"
                    size="mini" />
                </el-form-item>
                <el-form-item v-if="question.isOfficialQuestion" label="真题年份">
                  <el-date-picker :disabled="readonly" v-model="question.year" size="mini" value-format="yyyy"
                    type="year" placeholder="选择年份" />
                </el-form-item>
              </template>
              <el-form-item v-if="question.type === '4'" label="空格数量">
                <el-input-number :disabled="readonly" :min="1" v-model="question.blankSum" />
              </el-form-item>
              <el-form-item v-if="question.type === '7'" label="选项">
                <div class="line-question-container">
                  <div class="line-left-options">
                    <div v-for="(item, index) in question.options.left" :key="'left'+index" class="line-option">
                      <span class="option-index">{{ index + 1 }}.</span>
                      <el-input :disabled="readonly" :value="item.content" @input="val => $set(item, 'content', val)" placeholder="左侧选项" size="small" />
                      <el-button v-if="!readonly" type="danger" icon="el-icon-delete" circle size="mini"
                        @click="removeOption(index, 'left')" />
                    </div>
                  </div>
                  <div class="line-right-options">
                    <div v-for="(item, index) in question.options.right" :key="'right'+index" class="line-option">
                      <span class="option-index">{{ index + 1 }}.</span>
                      <el-input :disabled="readonly" :value="item.content" @input="val => $set(item, 'content', val)" placeholder="右侧选项" size="small" />
                      <el-button v-if="!readonly" type="danger" icon="el-icon-delete" circle size="mini"
                        @click="removeOption(index, 'right')" />
                    </div>
                  </div>
                  <el-button v-if="!readonly" type="primary" icon="el-icon-plus" circle size="mini"
                    style="position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%);"
                    @click="addOption" />
                </div>
              </el-form-item>
              <el-form-item v-if="
              question.type === '1'
            " label="答案">
                <el-radio-group :disabled="readonly" v-model="question.answer[0]" @change="handleAnswer">
                  <div v-for="item in question.select" :key="item.select">
                    <el-radio :label="item.select">
                      <el-select :disabled="readonly" v-model="item.select" style="width: 65px" size="small"
                        placeholder>
                        <el-option v-for="item in selectNotUse" :key="item" :label="item" :value="item" />
                      </el-select>
                      <myEdit :disabled="readonly" v-model="item.content" :inline="true" :use-dialog="true"
                        size="small" />
                      <el-link :disabled="readonly" :underline="false" icon="el-icon-error" type="danger"
                        @click="removeItem(item)" />
                    </el-radio>
                  </div>
                </el-radio-group>
                <div v-if="!readonly">
                  <el-link :underline="false" icon="el-icon-circle-plus" type="primary" @click="addItem" />
                </div>
              </el-form-item>
              <el-form-item v-if="
                  question.type === '2'
                " label="答案">
                <el-checkbox-group :disabled="readonly" v-model="question.answer" @change="handleAnswer">
                  <div v-for="item in question.select" :key="item.select">
                    <el-checkbox :label="item.select">
                      <el-select :disabled="readonly" v-model="item.select" style="width: 65px" size="small"
                        placeholder>
                        <el-option v-for="item in selectNotUse" :key="item" :label="item" :value="item" />
                      </el-select>
                      <myEdit :disabled="readonly" v-model="item.content" :inline="true" :use-dialog="true"
                        size="small" />
                      <el-link :disabled="readonly" :underline="false" icon="el-icon-error" type="danger"
                        @click="removeItem(item)" />
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
                <div v-if="!readonly" disabled>
                  <el-link :underline="false" icon="el-icon-circle-plus" type="primary" @click="addItem" />
                </div>
              </el-form-item>
              <el-form-item v-if="
              question.type === '3'
            " label="答案">
                <el-radio-group :disabled="readonly" v-model="question.answer[0]" @change="handleAnswer">
                  <div v-for="item in question.select" :key="item.select">
                    <el-radio :label="item.select">
                      <el-select :disabled="readonly" v-model="item.select" style="width: 65px" size="small"
                        placeholder>
                        <el-option v-for="item in selectNotUse" :key="item" :label="item" :value="item" />
                      </el-select>
                      <myEdit :disabled="readonly" v-model="item.content" :inline="true" :use-dialog="true"
                        size="small" />
                    </el-radio>
                  </div>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if=" question.type ==='4'" label="答案">
                <template v-for="index in question.blankSum">
                  <el-input :key="index" :disabled="readonly" v-model="question.answer[index-1]" />
                </template>
              </el-form-item>
              <el-form-item v-if="
                  question.type === '5'
                " label="答案">
                <myEdit :disabled="readonly" v-model="question.answer[0]" />
              </el-form-item>
              <el-form-item v-else-if="question.type === '7'" label="答案">
                <div class="line-question-container">
                  <div class="line-connections">
                    <div v-for="(item, index) in question.answer" :key="'conn'+index" class="line-connection">
                      <span class="connection-index">{{ index + 1 }}.</span>
                      <el-select :disabled="readonly" v-model="item.left" placeholder="左侧选项" size="small"
                        @change="validateConnection(item.index)">
                        <el-option v-for="(opt, idx) in question.options.left" :key="idx"
                          :label="(idx + 1) + '. ' + opt.content" :value="idx + 1"
                          :disabled="isLeftOptionUsed(idx + 1, item.index)" />
                      </el-select>
                      <span class="line-connection-arrow">→</span>
                      <el-select :disabled="readonly" v-model="item.right" placeholder="右侧选项" size="small"
                        @change="validateConnection(item.index)">
                        <el-option v-for="(opt, idx) in question.options.right" :key="idx"
                          :label="(idx + 1) + '. ' + opt.content" :value="idx + 1"
                          :disabled="isRightOptionUsed(idx + 1, item.index)" />
                      </el-select>
                      <el-button v-if="!readonly" type="danger" icon="el-icon-delete" circle size="mini"
                        @click="removeConnection(item.index)" />
                    </div>
                    <el-button v-if="!readonly" type="primary" icon="el-icon-plus" circle size="mini"
                      @click="addConnection" />
                  </div>
                </div>
              </el-form-item>
              <div v-if="
                  question.type === '1' ||
                  question.type === '2' ||
                  question.type === '3' ||
                  question.type === '4' ||
                  question.type === '5' ||
                  question.type === '7'
                ">
                <el-form-item label="解析">
                  <div style="display: flex; align-items: center;">
                    <myEdit :disabled="readonly" v-model="question.analyze" style="flex: 1;" />
                    <el-button v-if="!readonly" type="primary" size="small" style="margin-left: 10px;" @click="handleAiAnalyze" :loading="aiAnalyzeLoading">AI解析</el-button>
                  </div>
                </el-form-item>
              </div>
              <el-form-item label="难易程度">
                <el-rate :disabled="readonly" v-model="question.difficultyLevel" />
              </el-form-item>
              <el-form-item label="相关知识点">
                <draggable :disabled="readonly" v-model="knowledgePoints" style="display: inline-block"
                  @update="updateSort">
                  <el-tag v-for="knowledgePoint in knowledgePoints" :key="knowledgePoint.id" :closable="!readonly"
                    @close="handleClose(knowledgePoint)">{{ knowledgePoint.name }}</el-tag>
                </draggable>
                <el-button v-if="!readonly" class="button-new-tag" size="small" @click="open()">+ New</el-button>
              </el-form-item>
              <!-- <el-form-item v-else label="相关知识点">
                <el-tag type="warning">暂存题目后方可添加知识点</el-tag>
              </el-form-item> -->
              <el-form-item>
                <el-button v-if="!readonly" type="info" @click="saveQuestion(false)">暂存</el-button>
                <el-button v-if="!readonly" type @click="saveQuestion(true)">暂存并继续添加</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <el-card v-if="
            question.type === '6'
          " class="box-card">
          <div slot="header" class="clearfix">
            <el-row :gutter="20">
              <el-col :span="20" class="cardHeader">
                <span>
                  子题目
                  <span>(注*支持拖拽排序)</span>
                </span>
              </el-col>
              <el-col :span="4" class="cardHeader">
                <el-button v-if="!readonly && question.id" type="primary" size="mini"
                  @click="saveSonQuestion()">添加子题目</el-button>
              </el-col>
            </el-row>
          </div>
          <draggable :disabled="readonly" v-model="sonQuestions" @update="updateSortQuestion">
            <el-card v-for="(sonQuestion, index) in sonQuestions" :key="sonQuestion.id" class="questionItem">
              <el-row>
                <el-col :span="1">题目:</el-col>
                <el-col :span="1">{{ index + 1 }}</el-col>
                <el-col :span="1" class="fg">|</el-col>
                <el-col :span="10">
                  <span class="questionTitle" v-html="sonQuestion.title" />
                </el-col>
                <el-col :span="2">
                  <el-tag effect="dark" size="mini">{{
                    questionType[sonQuestion.type]
                    }}</el-tag>
                </el-col>
                <el-col :span="1" class="fg">|</el-col>
                <el-col :span="2">
                  <el-tag :type="sonQuestion | tag" size="mini">{{
                    sonQuestion | status
                    }}</el-tag>
                </el-col>
                <el-col v-if="!readonly" :span="1" class="fg">|</el-col>
                <el-col v-if="!readonly" :span="2">
                  <el-link icon="el-icon-edit" @click="sonQuestionInfo(sonQuestion.id)">编辑</el-link>
                </el-col>
                <el-col v-if="!readonly" :span="1" class="fg">|</el-col>
                <el-col v-if="!readonly" :span="2">
                  <el-link icon="el-icon-delete" type="danger" @click="deleteQuestion(sonQuestion.id)">删除</el-link>
                </el-col>
              </el-row>
            </el-card>
          </draggable>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="phoneShow">
          <div class="phoneContent">
            <phone :question="questionShow" :parent-question="parentQuestionShow" :knowledge-points="knowledgePoints" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- AI解析弹窗 -->
    <el-dialog :visible.sync="aiAnalyzeDialogVisible" title="AI解析结果" width="40%" :before-close="closeAiAnalyzeDialog">
      <div v-loading="aiAnalyzeLoading">
        <div v-if="aiAnalyzeResult">
          <h4>AI解析结果：</h4>
          <div class="ai-analyze-content">
            <div v-if="aiAnalyzeResult.answer">
              <h5>答案：</h5>
              <div v-html="aiAnalyzeResult.answer"></div>
            </div>
            <div v-if="aiAnalyzeResult.analyze">
              <h5>解析：</h5>
              <div v-html="aiAnalyzeResult.analyze"></div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAiAnalyzeDialog">取 消</el-button>
        <el-button type="primary" @click="adoptAiAnalyze">采 纳</el-button>
      </span>
    </el-dialog>

    <!-- AI判断知识点弹窗 -->
    <el-dialog :visible.sync="aiKnowledgeDialogVisible" title="AI判断知识点" width="50%" :before-close="closeAiKnowledgeDialog">
      <div v-loading="aiKnowledgeLoading">
        <div v-if="aiKnowledgeResult && aiKnowledgeResult.length > 0">
          <h4>AI推荐的知识点：</h4>
          <div class="ai-knowledge-content">
            <el-checkbox-group v-model="selectedKnowledgePoints">
              <div v-for="(item, index) in aiKnowledgeResult" :key="index" class="knowledge-item">
                <el-checkbox :label="item.pointId" :value="item.pointId">
                  <span class="knowledge-name">{{ item.name }}</span>
                  <span class="knowledge-confidence" v-if="item.confidence">(置信度: {{ item.confidence }}%)</span>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
        <div v-else-if="!aiKnowledgeLoading">
          <el-empty description="未能找到知识点"></el-empty>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAiKnowledgeDialog">取 消</el-button>
        <el-button type="primary" @click="adoptAiKnowledge" :disabled="selectedKnowledgePoints.length === 0">确 定</el-button>
      </span>
    </el-dialog>
    
    <el-dialog :visible="dialogFormVisible" title="知识点" width="25%" :before-close="beforeClose">
      <el-form :model="knowledgePointQuery" label-position="left" label-width="80px" class="knowledgePointForm">
        <!-- <el-form-item label="考试类型">
          <el-select v-model="knowledgePointQuery.testTypeId" clearable>
            <el-option
              v-for="item in testType"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属学科">
          <el-select v-model="knowledgePointQuery.subjectId" clearable>
            <el-option
              v-for="subjectType in subjectTypes"
              :key="subjectType.id"
              :label="subjectType.name"
              :value="subjectType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属学段">
          <el-select v-model="knowledgePointQuery.levelId" clearable>
            <el-option
              v-for="subjectType in schoolSections"
              :key="subjectType.id"
              :label="subjectType.name"
              :value="subjectType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属地区">
          <el-cascader
            v-model="knowledgePointQuery.area"
            :options="areaList"
            :props="{ checkStrictly: true }"
            placeholder="试试搜索：昆明"
            filterable
            show-all-levels
            clearable
          />
          <el-button @click="query()">查询</el-button>
        </el-form-item> -->
        <el-form-item label="知识点">
          <el-cascader ref="point" v-if="dialogFormVisible" v-model="point" :options="knowledgePointOptions"
            placeholder="请选择知识点" clearable />
          <el-button type="primary" @click="addKnowledgePoint(1)">添加</el-button>
          <el-button type="success" @click="aiJudgeKnowledgePoint" style="margin-left: 10px;">AI判断知识点</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" />
    </el-dialog>

  </div>
</template>

<script>
  import Sticky from "@/components/Sticky";
  import { uploadAli } from "@/api/upload.js";
  import myVideo from "@/components/video/myVideo";
  import draggable from "vuedraggable";
  import phone from "@/components/phone";
  import myEdit from "@/components/myEdit";
  import SelectTeacher from "../test/components/SelectTeacher";
  import Msg from "@/views/test/components/Msg";

  import { addQuestionToTest, getquestionScore } from "@/api/test.js";
  import {
    searchPoint,
    queryQuestionPoint,
    saveQuestionPoint,
    deleteQuestionPoint,
    questionPointSort,
    knowledgePointExceedLimit,
  } from "@/api/point.js";
  import {
    questionList,
    saveQuestion,
    questionInfo,
    commitCheck,
    rejectCheck,
    commitReview,
    rejectReview,
    deleteQuestion,
    review,
    questionSort,
    saveQuestionInfoLog,
    questionUpAndDown,
    searchQuestionList,
    aiAnalyzeQuestion,
    aiJudgeKnowledge,
  } from "@/api/question.js";
  import katex from "@/components/phone/katex";
  import { getAreaList } from "@/api/area.js";

  import { getSubjectList } from "@/api/subjectType.js";
  import { getTestTypeList } from "@/api/testType.js";
  export default {
    name: "QuestionInfo",
    components: {
      Sticky,
      myVideo,
      draggable,
      phone,
      myEdit,
      SelectTeacher,
      katex,
      Msg,
    },
    filters: {
      tag(row) {
        if (row.onlineStatus === 1) {
          return "success";
        }
        return "";
      },
      status(row) {
        if (row.onlineStatus === 1) {
          return "上线";
        }
        if (row.status === 0) {
          return "编辑中";
        }
        if (row.status == 3) {
          return "校验中";
        }
        if (row.status == 4) {
          return "审核中";
        }
        if (row.status == 5) {
          return "已审核";
        }
        return "下线";
      },
    },
    data() {
      return {
        testQuestionIdList: [],
        updateVisible: false,
        // AI解析相关数据
        aiAnalyzeDialogVisible: false,
        aiAnalyzeLoading: false,
        aiAnalyzeResult: null,
        // AI判断知识点相关数据
        aiKnowledgeDialogVisible: false,
        aiKnowledgeLoading: false,
        aiKnowledgeResult: [],
        selectedKnowledgePoints: [],
        rules: {
          subjectId: [{ required: true, message: "科目必填" }],
        },
        updateQusestions: [
          {
            operation: "1",
            changePosition: "题目",
            changeType: "2",
            oldContent: "",
            newContent: "",
          },
        ],
        initknowledgePoint: true,
        isknowledgePoint: false,
        loading: false,
        testType: [],
        subjectTypes: [],
        areaList: [],
        schoolSections: [],
        questionShow: {},
        parentQuestionShow: {},
        editContent: "",
        loading: false,
        point: "",
        knowledgePointOptions: [],
        subjects: [],
        teacher: [],
        teacherSubject: [],
        knowledgePointQuery: {},
        knowledgePointList: [],
        knowledgePoints: [],
        radio: "1",
        sonQuestions: [],
        qPoint: "",
        dialogFormVisible: false,
        video: {
          sources: [],
          options: {
            autoplay: false,
            poster: "",
          },
        },
        videoUploadStatus: 0,
        percentage: 0,
        selectAnswer: [
          "A",
          "B",
          "C",
          "D",
          "E",
          "F",
          "G",
          "H",
          "I",
          "J",
          "K",
          "L",
          "M",
          "N",
          "O",
          "P",
          "Q",
          "R",
          "S",
          "T",
          "U",
          "V",
          "W",
          "X",
          "Y",
          "Z",
        ],
        questionType: {
          1: "单选题",
          2: "多选题",
          3: "判断题",
          4: "填空",
          5: "简答题",
          6: "材料题",
          7: "连线题",
        },
        newSelect: {
          select: "",
          content: "",
        },
        test: {
          id: null,
        },
        isEdit: false,
        initSubject: true,
        parentQuestion: {
          id: null,
          title: "",
        },
        beSimilarQuestion: [],
        question: {
          id: null,
          testStructure: "",
          blankSum: 1,
          select: [
            {
              select: "A",
              content: "",
            },
            {
              select: "B",
              content: "",
            },
            {
              select: "C",
              content: "",
            },
            {
              select: "D",
              content: "",
            },
          ],
          options: {
            left: [
              { index: 1, content: '' },
              { index: 2, content: '' },
              { index: 3, content: '' }
            ],
            right: [
              { index: 1, content: '' },
              { index: 2, content: '' },
              {idnex:3,content:''}
            ]
          },
          answer: [
          ],
          score: 1,
          type: "1",
          title: "",
          videoAnalyze: "",
          analyze: "",
          difficultyLevel: 1,
          questionType: 1,
          isOfficialQuestion: 0,
          officialQuestionSource: "",
          year: "",
          subjectId: "",
        },
        questionChangeLogId: undefined,
        search: true,
        questionUpAndDown: {
          up: undefined,
          down: undefined,
        },
        questionUpDisabled: true,
        questionDownDisabled: true,
        testQuestionList: [],
        subjectOptions: [],
        defaultOptions: {
          left: [
            { index: 1, content: '' },
            { index: 2, content: '' },
            { index: 3, content: '' }
          ],
          right: [
            { index: 1, content: '' },
            { index: 2, content: '' },
            { index: 3, content: '' }
          ]
        }
      };
    },
    computed: {
      testUpDisabled() {
        let index = this.testQuestionIdList.indexOf(this.question.id);
        return index == 0;
      },
      testDownDisabled() {
        let index = this.testQuestionIdList.indexOf(this.question.id);
        return index == this.testQuestionIdList.length - 1;
      },
      typeName() {
        return this.questionType[this.question.type];
      },
      selectNotUse() {
        const arr = this.selectAnswer.filter((item) => {
          const x = this.question.select.find((s) => s.select === item);
          return !x;
        });
        return arr;
      },
      readonly: function () {
        return (
          (!this.isEdit || this.question.readonly) && this.question.id != null
        );
      },
    },
    watch: {
      question: {
        handler(newValue, old) {
          if (newValue.title && newValue.title.length > 4) {
            if (this.search) {
              let title = newValue.title;
              if (title.length > 800) {
                title = title.substring(0, 800);
              }
            }
          } else {
            this.beSimilarQuestion = [];
            this.search = true;
          }
          this.questionShow = this.question;
          this.parentQuestionShow = this.parentQuestion;
        },
        deep: true,
      },
      parentQuestion: {
        handler(newValue, old) {
          this.parentQuestionShow = this.parentQuestion;
        },
        deep: true,
      },
    },
    created() {
      // 初始化左右选项和答案数组
      if (!this.question.options.left || this.question.options.left.length === 0) {
        this.question.options.left = JSON.parse(JSON.stringify(this.defaultOptions.left));
      }
      if (!this.question.options.right || this.question.options.right.length === 0) {
        this.question.options.right = JSON.parse(JSON.stringify(this.defaultOptions.right));
      }
      // 确保连线题的answer数组正确初始化
      if (this.question.type === '7' && (!Array.isArray(this.question.answer) || this.question.answer.length === 0)) {
        const initialAnswers = this.question.options.left.map((item, index) => ({
          left: item.index,
          right: undefined,
          index: index
        }));
        this.$set(this.question, 'answer', initialAnswers);
      }
      if (this.question.lineOptions) {
        this.question.options = JSON.parse(this.question.lineOptions)
      }
      const test = this.$router.currentRoute.params.test;
      this.test = this.$router.currentRoute.params.test || this.test;
      if (this.test && this.test.testStructures) {
        this.test.testStructures.forEach((element) => {
          if (element.question) {
            element.question.forEach((res) => {
              this.testQuestionIdList.push(res.questionId);
              this.testQuestionList.push({
                questionId: res.questionId,
                score: res.score,
                testStructureId: element.id,
              });
            });
          }
        });
      }
      if (this.test.id) {
        this.question.testId = this.test.id;
        this.question.isOfficialQuestion = 1;
        this.question.officialQuestionSource = this.test.title;
        this.question.year = this.test.year;
      }
      if (this.$router.currentRoute.params.question) {
        this.question.id = this.$router.currentRoute.params.question.id;
        this.question.score = this.$router.currentRoute.params.question.score;
      }
      this.getSubject()
      this.questionInfo();
      this.getQuestionUpAndDown();
    },
    methods: {
      // AI解析相关方法
      handleAiAnalyze() {
        // 检查题目是否为空
        if (!this.question.title) {
          this.$message.warning('请先输入题目内容再进行AI解析');
          return;
        }
        
        this.aiAnalyzeLoading = true;
        this.aiAnalyzeDialogVisible = true;
        console.log(this.question.title);
        // 准备选项数据
        let select = null;
        if ([1, 2, 3].includes(Number(this.question.type))) { // 单选、多选、判断题
          select = JSON.stringify(this.question.select);;
        }
        
        // 调用AI解析API，传递所有必要参数（type传对应的中文）
        aiAnalyzeQuestion(
          this.question.title, 
          this.questionType[this.question.type], // 将数字类型转换为中文描述
          this.parentQuestion.materials, 
          select
        )
          .then(res => {
            if (res.code ==0) {
              this.aiAnalyzeResult = res.data;
            } else {
              this.$message.error(res.msg || 'AI解析失败');
            }
          })
          .catch(err => {
            console.error('AI解析出错:', err);
            this.$message.error('AI解析服务异常，请稍后再试');
          })
          .finally(() => {
            this.aiAnalyzeLoading = false;
          });
      },
      
      closeAiAnalyzeDialog() {
        this.aiAnalyzeDialogVisible = false;
        this.aiAnalyzeResult = null;
      },
      
      adoptAiAnalyze() {
        if (!this.aiAnalyzeResult) {
          this.$message.warning('没有可采纳的AI解析结果');
          return;
        }
        
        // 根据题目类型处理答案
        if (this.aiAnalyzeResult.answer) {
          this.$set(this.question, 'answer',JSON.parse(this.aiAnalyzeResult.answer));
        }
        
        // 设置解析
        if (this.aiAnalyzeResult.analyze) {
          this.question.analyze = this.aiAnalyzeResult.analyze;
        }
        
        this.$message.success('已采纳AI解析结果');
        this.closeAiAnalyzeDialog();
      },
      
      // AI判断知识点
      aiJudgeKnowledgePoint() {
        if (!this.question.title && this.question.type !== '6') {
          this.$message.warning('请先填写题目内容');
          return;
        }
        
        if (this.question.type === '6' && !this.question.materials) {
          this.$message.warning('材料题请先填写材料内容');
          return;
        }
        
        this.aiKnowledgeDialogVisible = true;
        this.aiKnowledgeLoading = true;
        this.selectedKnowledgePoints = [];
        
        // 构建题目内容
        let questionContent = '';
        if (this.question.type === '6') {
          // 材料题：父级材料 + 题目
          questionContent = (this.parentQuestion.materials || this.question.materials || '') + (this.question.title || '');
        } else {
          // 普通题目
          if (this.parentQuestion.materials) {
            // 存在材料的情况：父级材料 + 题目
            questionContent = this.parentQuestion.materials + this.question.title;
          } else {
            // 不存在材料：只有题目
            questionContent = this.question.title;
          }
        }
        
        // 获取叶子节点知识点列表
        const leafKnowledgePoints = this.getLeafKnowledgePoints(this.knowledgePointOptions);
        
        // 检查知识点列表是否为空
        if (!leafKnowledgePoints || leafKnowledgePoints.length === 0) {
          this.$message.warning('知识点列表为空，无法进行AI判断');
          this.aiKnowledgeLoading = false;
          this.aiKnowledgeDialogVisible = false;
          return;
        }
        
        // 调用AI判断知识点API
        this.callAiJudgeKnowledgeAPI(questionContent,JSON.stringify (leafKnowledgePoints));
      },
      
      // 获取知识点选项的叶子节点
      getLeafKnowledgePoints(options, result = []) {
        options.forEach(option => {
          if (!option.children || option.children.length === 0) {
            // 叶子节点
            result.push({
              pointId: option.value,
              name: option.label
            });
          } else {
            // 继续递归查找叶子节点
            this.getLeafKnowledgePoints(option.children, result);
          }
        });
        return result;
      },
      
      // 调用AI判断知识点API
       callAiJudgeKnowledgeAPI(questionContent, knowledgePoints) {
         // 调用真实的API接口
         aiJudgeKnowledge(questionContent, knowledgePoints)
           .then(res => {
             if (res.code == 0) {
               // 处理接口返回的知识点名称列表
               const knowledgeNameList = res.data || [];
               if (knowledgeNameList.length === 0) {
                 this.$message.warning('未能找到相关知识点');
                 this.aiKnowledgeDialogVisible = false;
                 this.aiKnowledgeResult = [];
               } else {
                 this.aiKnowledgeResult = this.convertNamesToKnowledgePoints(knowledgeNameList, JSON.parse(knowledgePoints));
               }
             } else {
               this.$message.error(res.msg || 'AI判断知识点失败');
               this.aiKnowledgeResult = [];
             }
           })
           .catch(err => {
             console.error('AI判断知识点出错:', err);
             this.$message.error('AI判断知识点服务异常，请稍后再试');
             this.aiKnowledgeResult = [];
             
             // 如果API调用失败，提供模拟数据作为备选方案
             if (knowledgePoints.length > 0) {
               const mockResult = knowledgePoints.slice(0, 3).map((point, index) => ({
                 pointId: point.pointId,
                 name: point.name,
                 confidence: 90 - index * 10 // 模拟置信度
               }));
               this.aiKnowledgeResult = mockResult;
               this.$message.info('使用模拟数据展示功能效果');
             }
           })
           .finally(() => {
             this.aiKnowledgeLoading = false;
           });
       },
       
       // 将知识点名称列表转换为包含pointId的对象数组
       convertNamesToKnowledgePoints(nameList, allKnowledgePoints) {
         const result = [];
         nameList.forEach(name => {
           // 在所有知识点中查找匹配的名称
           const matchedPoint = allKnowledgePoints.find(point => point.name === name);
           if (matchedPoint) {
             result.push({
               pointId: matchedPoint.pointId,
               name: matchedPoint.name
             });
           } else {
             // 如果没有找到匹配的pointId，可能是新的知识点，给一个临时ID
             console.warn(`未找到知识点"${name}"对应的pointId`);
             result.push({
               pointId: `temp_${Date.now()}_${Math.random()}`,
               name: name
             });
           }
         });
         return result;
       },
      // 关闭AI判断知识点弹窗
      closeAiKnowledgeDialog() {
        this.aiKnowledgeDialogVisible = false;
        this.aiKnowledgeResult = [];
        this.selectedKnowledgePoints = [];
        // 同时关闭原始知识点弹窗
        this.dialogFormVisible = false;
      },
      
      // 采纳AI推荐的知识点
      adoptAiKnowledge() {
        if (this.selectedKnowledgePoints.length === 0) {
          this.$message.warning('请选择要添加的知识点');
          return;
        }
        
        // 添加选中的知识点
        this.selectedKnowledgePoints.forEach(pointId => {
          const knowledgePoint = this.aiKnowledgeResult.find(item => item.pointId === pointId);
          if (knowledgePoint) {
            // 检查是否已存在该知识点
            const exists = this.knowledgePoints.some(point => point.pointId === pointId);
            if (!exists) {
              const point = {
                pointId: knowledgePoint.pointId,
                name: knowledgePoint.name
              };
              
              // 检查知识点关联题目数量限制
              knowledgePointExceedLimit(point.pointId).then((res) => {
                if (res.data) {
                  this.$message({
                    message: `警告：知识点"${point.name}"已关联10道或10道以上题目，建议一个知识点不要关联超过10道题目`,
                    type: 'warning',
                    duration: 8000,
                  });
                }
              });
              
              if (this.knowledgePoints) {
                this.knowledgePoints.push(point);
              } else {
                this.knowledgePoints = [point];
              }
            }
          }
        });
        
        this.$message.success(`已添加 ${this.selectedKnowledgePoints.length} 个知识点`);
        this.closeAiKnowledgeDialog();
      },
      
      changeQuestionType() {
        this.question.options = {}
        if (this.question.type == 1 || this.question.type == 2 || this.question.type == 3 || this.question.type == 4 || this.question.type == 7) {
          this.question.answer = []
        }
        if (this.question.type == 3) {
          this.question.select = [
            {
              select: "A",
              content: "对",
            },
            {
              select: "B",
              content: "错",
            }
          ]
        }
        if (this.question.type === '7') {
          // 确保连线题的选项结构正确初始化
          this.question.options = {
            left: [
              { content: '', index: 1 },
              { content: '', index: 2 },
              { content: '', index: 3 }
            ],
            right: [
              { content: '', index: 1 },
              { content: '', index: 2 },
              { content: '', index: 3 }
            ]
          }
        }
      },
      isLeftOptionUsed(leftIndex, currentConnectionIndex) {
        // 由于传入的leftIndex已经是从1开始的，所以不需要再加1
        return this.question.answer.some((conn, idx) =>
          idx !== currentConnectionIndex && conn.left === leftIndex
        );
      },
      isRightOptionUsed(rightIndex, currentConnectionIndex) {
        // 由于传入的rightIndex已经是从1开始的，所以不需要再加1
        return this.question.answer.some((conn, idx) =>
          idx !== currentConnectionIndex && conn.right === rightIndex
        );
      },
      validateConnection(index) {
        const connection = this.question.answer[index];
        if (connection.left !== undefined && connection.right !== undefined) {
          // 检查是否有重复的左侧选项
          const leftDuplicate = this.question.answer.some((conn, idx) =>
            idx !== index && conn.left === connection.left
          );
          // 检查是否有重复的右侧选项
          const rightDuplicate = this.question.answer.some((conn, idx) =>
            idx !== index && conn.right === connection.right
          );

          if (leftDuplicate || rightDuplicate) {
            // 如果有重复，使用$set更新连接状态
            if (leftDuplicate) this.$set(connection, 'left', undefined);
            if (rightDuplicate) this.$set(connection, 'right', undefined);
          }
        }
      },
      addOption() {
        console.log(this.question.options)
        if (!this.question.options) {
          this.question.options = {
            left: [],
            right: []
          }
        }
        const leftIndex = this.question.options.left.length + 1;
        const rightIndex = this.question.options.right.length + 1;
        this.question.options.left.push({ content: '', index: leftIndex });
        this.question.options.right.push({ content: '', index: rightIndex });
      },
      removeOption(index, side) {
        this.question.options[side].splice(index, 1);
        // 更新剩余选项的index值
        this.question.options[side].forEach((option, idx) => {
          option.index = idx + 1;
        });
        // 更新连线关系，由于索引从1开始，需要处理对应关系
        if (side === 'left') {
          this.question.answer = this.question.answer.filter(conn => conn.left !== index + 1);
          // 更新大于当前索引的连接
          this.question.answer.forEach(conn => {
            if (conn.left > index + 1) conn.left--;
          });
        } else {
          this.question.answer = this.question.answer.filter(conn => conn.right !== index + 1);
          // 更新大于当前索引的连接
          this.question.answer.forEach(conn => {
            if (conn.right > index + 1) conn.right--;
          });
        }
      },
      addConnection() {
        if (!this.question.answer) {
          this.$set(this.question, 'answer', []);
        }
        const newConnection = { left: undefined, right: undefined, index: this.question.answer.length };
        this.$set(this.question.answer, this.question.answer.length, newConnection);
      },
      removeConnection(index) {
        this.question.answer.splice(index, 1);
        // 更新剩余连接的index，并使用$set确保视图更新。
        this.question.answer.forEach((conn, idx) => {
          this.$set(conn, 'index', idx);
        });
      },
      testQuestionUp() {
        let index = this.testQuestionIdList.indexOf(this.question.id);
        this.question.id = this.testQuestionIdList[index - 1];
        let testQuestion = this.testQuestionList.find(
          (res) => res.questionId == this.question.id
        );
        this.question.score = testQuestion.score;
        this.test.testStructure = testQuestion.testStructureId;
        this.questionInfo();
      },
      testQuestionDown() {
        let index = this.testQuestionIdList.indexOf(this.question.id);
        this.question.id = this.testQuestionIdList[index + 1];
        let testQuestion = this.testQuestionList.find(
          (res) => res.questionId == this.question.id
        );
        this.question.score = testQuestion.score;
        this.test.testStructure = testQuestion.testStructureId;
        this.questionInfo();
      },
      uploadLog() {
        saveQuestionInfoLog(this.questionChangeLogId, this.updateQusestions).then(
          (res) => {
            this.beforeClose();
            this.$message({
              type: "success",
              message: "修改报备成功!",
            });
          }
        );
      },
      deleLog(index) {
        this.updateQusestions.splice(index, 1);
      },
      addLog() {
        this.updateQusestions.push({
          operation: "1",
          changePosition: "题目",
          changeType: "2",
          oldContent: "",
          newContent: "",
        });
      },
      beforeClose() {
        this.dialogFormVisible = false;
        this.updateVisible = false;
        this.questionChangeLogId = undefined;
        this.updateQusestions = [
          {
            operation: "1",
            changePosition: "题目",
            changeType: "2",
            oldContent: "",
            newContent: "",
          },
        ];
      },
      open() {
        this.dialogFormVisible = true;
        this.query();
      },
      bindQuestion() {
        addQuestionToTest(
          this.test.id,
          this.test.testStructure,
          this.question.id,
          this.question.score
        )
          .then((res) => {
            this.$confirm("关联成功,是否继续添加?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "danger",
            })
              .then(() => {
                this.question = {
                  id: null,
                  testStructure: "",
                  select: [
                    {
                      select: "A",
                      content: "",
                    },
                    {
                      select: "B",
                      content: "",
                    },
                    {
                      select: "C",
                      content: "",
                    },
                    {
                      select: "D",
                      content: "",
                    },
                  ],
                  answer: [
                  ],
                  score: 1,
                  type: "1",
                  title: "",
                  videoAnalyze: "",
                  analyze: "",
                  difficultyLevel: 1,
                  questionType: 1,
                  isOfficialQuestion: 0,
                  officialQuestionSource: "",
                  year: "",
                  options: {
                    left: [
                      { index: 0, content: '' },
                      { index: 1, content: '' },
                      { index: 2, content: '' }
                    ],
                    right: [
                      { index: 0, content: '' },
                      { index: 1, content: '' },
                      { index: 2, content: '' }
                    ]
                  },
                };
                this.parentQuestion = {
                  id: null,
                  title: "",
                };
                this.sonQuestions = [];
              })
              .catch(() => {
                this.$router.push({
                  path: "/testInfo",
                  query: {
                    id: this.test.id,
                  },
                });
              });
          })
          .catch((err) => {
            this.$confirm("题目与试卷关联失败,是否重新关联?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "danger",
            })
              .then(() => {
                addQuestionToTest(
                  this.test.id,
                  this.test.testStructure,
                  this.question.id,
                  this.question.score
                )
                  .then((res) => {
                    this.question.score = res.data;
                    let testQuestion = this.testQuestionList.find(
                      (res) => res.questionId == this.question.id
                    );
                    if (testQuestion) {
                      testQuestion.score = res.data;
                    }
                  })
                  .catch((err) => console.log(err));
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消关联",
                });
              });
          });
      },
      query() {
        this.isknowledgePoint = false;
        this.initknowledgePoint = true;
        this.$nextTick(() => {
          this.isknowledgePoint = true;
        });
      },

      deleteQuestion(id) {
        deleteQuestion(id).then((res) => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          questionList({
            parentId: this.question.id,
            sort: "asc_q.sort",
            pageNo: 1,
            pageSize: 40,
          }).then((res) => {
            this.sonQuestions = res.data.list;
          });
        });
      },
      queryPoint() {
        if (this.question.subjectId instanceof Array) {
          this.knowledgePointQuery.specificationTypeId = this.question.subjectId[this.question.subjectId.length - 1];
        } else {
          this.knowledgePointQuery.specificationTypeId = this.question.subjectId
        }
        searchPoint(this.knowledgePointQuery).then((res) => {
          const transformData = (data) => {
            return data.map(item => ({
              value: item.id,
              label: item.name,
              children: item.children ? transformData(item.children) : undefined
            }));
          };
          this.knowledgePointOptions = transformData(res.data);
        });
      },
      querySearchAsync(str) {
        if (str) {
          this.loading = true;
          searchPoint({ name: str }).then((res) => {
            this.knowledgePointList = res.data;
            this.loading = false;
          });
        }
      },
      showQuestion(id) {
        this.question.id = id;
        this.parentQuestion = {
          id: null,
          title: "",
        };
        this.questionInfo();
      },
      show(id) {
        questionInfo(id).then((res) => {
          const data = res.data;
          if (data.answer) {
            data.answer = JSON.parse(data.answer);
          }
          this.questionShow = data;
          if (this.questionShow.parentId !== 0) {
            questionInfo(this.questionShow.parentId).then((item) => {
              this.parentQuestionShow = item.data;
            });
          }
        });
      },
      updateSortQuestion(evt) {
        const changeTags = this.sonQuestions[evt.newIndex];
        let sort;
        let beforeSort;
        let afterSort;
        if (evt.newIndex === 0) {
          beforeSort = this.sonQuestions[evt.newIndex + 1].sort - 50;
        } else {
          beforeSort = this.sonQuestions[evt.newIndex - 1].sort;
        }
        if (evt.newIndex === this.sonQuestions.length - 1) {
          afterSort = this.sonQuestions[evt.newIndex - 1].sort + 50;
        } else {
          afterSort = this.sonQuestions[evt.newIndex + 1].sort;
        }
        sort =
          Math.floor(Math.random() * (afterSort - beforeSort + 1)) + beforeSort;
        questionSort(changeTags.id, sort).then((res) => {
          questionList({
            parentId: this.question.id,
            sort: "asc_q.sort",
            pageNo: 1,
            pageSize: 40,
          }).then((res) => {
            this.sonQuestions = res.data.list;
          });
        });
      },
      sonQuestionInfo(id) {
        this.parentQuestion=this.question
        this.question.id = id;
        this.questionInfo();
      },
      goBack() {
        this.question = {
          id: this.question.parentId,
        };
        this.parentQuestion = {
          id: null,
          title: "",
        };
        this.questionInfo();
      },
      saveSonQuestion() {
        
        this.parentQuestion = this.question;
        this.question = {
          id: null,
          testStructure: "",
          blankSum: 1,
          select: [
            {
              select: "A",
              content: "",
            },
            {
              select: "B",
              content: "",
            },
            {
              select: "C",
              content: "",
            },
            {
              select: "D",
              content: "",
            },
          ],
          options: {
            left: [
              { index: 0, content: '' },
              { index: 1, content: '' },
              { index: 2, content: '' }
            ],
            right: [
              { index: 0, content: '' },
              { index: 1, content: '' },
              { index: 2, content: '' }
            ]
          },
          parentId: this.parentQuestion.id,
          answer: [
          ],
          score: 1,
          type: "1",
          title: "",
          videoAnalyze: "",
          analyze: "",
          difficultyLevel: 1,
          questionType: 1,
          isOfficialQuestion: 0,
          officialQuestionSource: "",
          year: "",
          subjectId: "",
        };
        this.knowledgePoints = [];
      },
      rejectReview() {
        const h = this.$createElement;
        this.$msgbox({
          title: "驳回",
          message: h(Msg, {
            props: { store: this.$store },
          }),
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: (action, instance, done) => {
            done();
          },
        })
          .then((res) =>
            rejectReview(this.question.id, this.$store.getters.msg).then((res) =>
              this.questionInfo()
            )
          )
          .catch((err) => console.log(err));
      },
      review() {
        review(this.question.id).then((res) => this.questionInfo());
      },
      questionInfo() {
        const id = this.question.id || this.$router.currentRoute.query.id;
        if (id) {

          this.question.id = id;
          questionList({
            parentId: id,
            sort: "asc_q.sort",
            pageNo: 1,
            pageSize: 40,
          }).then((res) => {
            this.sonQuestions = res.data.list;
          });
          questionInfo(id).then((res) => {
            const data = res.data;
            if (data.answer) {
              data.answer = JSON.parse(data.answer);
            }
            const score = this.question.score;
            this.question = res.data;
            if (!this.question.score) {
              this.question.score = score;
            }
            if (this.question.checkPeople === 0) {
              this.question.checkPeople = null;
            }
            if (this.question.reviewPeople === 0) {
              this.question.reviewPeople = null;
            }
            this.question.type = this.question.type + "";
            if (this.question.videoAnalyze) {
              this.videoUploadStatus = 2;
              this.video.sources.push({
                src: this.question.videoAnalyze,
                type: "video/mp4",
              });
            }
            if (this.question.year) {
              this.question.year = this.question.year + "";
            }
            if (this.question.questionType === 2) {
              questionInfo(this.question.parentId).then((res) => {
                this.parentQuestion = res.data;
              });
            }
            if (this.question.lineOptions) {
              this.$set(this.question, 'options', JSON.parse(this.question.lineOptions));
            }
            this.queryPoint()
            this.queryQuestionPoint();
          });
        }
      },
      saveQuestion(flag) {
        let vaildFlag;
        this.$refs["question"].validate((valid) => {
          vaildFlag = valid;
          if (!valid) {
            return false;
          }
        });
        if (!vaildFlag) {
          return;
        }
        const question = JSON.parse(JSON.stringify(this.question));
        if (question.type != 6) {
          if(!question.title){
          this.$message.error("题目不能为空")
          return
        }
          if (!question.answer || question.answer.length === 0) {
            this.$message.error("答案不能为空")
            return
          }else{
            console.log(question.answer)
            question.answer = question.answer.filter((item) => {
              return item !== undefined&&item!=null;
            });
          }
        }
        if(question.type == 6) {
          if(!question.materials||question.materials.length === 0) {
            this.$message.error("解析不能为空")
            return
          }
        }

        if (!question.name) {
          question.name = this.typeName;
        }
        localStorage.setItem("question_subject", question.subjectId);
        question.knowledgePoints = this.knowledgePoints;
        question.lineOptions = JSON.stringify(this.question.options)
        saveQuestion(question).then((res) => {
          this.question.id = res.data.id;
          this.knowledgePoints = res.data.knowledgePoints;
          if (res.data.questionChangeLogId) {
            this.updateVisible = true;
            this.questionChangeLogId = res.data.questionChangeLogId;
          }
          this.newSelect = {
            select: "",
            content: "",
          };
          if (this.test.id) {
            addQuestionToTest(
              this.test.id,
              this.test.testStructure,
              this.question.id,
              this.question.score
            )
              .then((res) => {
                this.question.score = res.data;
                let testQuestion = this.testQuestionList.find(
                  (res) => res.questionId == this.question.id
                );
                if (testQuestion) {
                  testQuestion.score = res.data;
                }
              })
              .catch((err) => {
                this.$confirm("题目与试卷关联失败,是否重新关联?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "danger",
                })
                  .then(() => {
                    addQuestionToTest(
                      this.test.id,
                      this.test.testStructure,
                      this.question.id,
                      this.question.score
                    )
                      .then((res) => {
                        this.question.score = res.data;
                        let testQuestion = this.testQuestionList.find(
                          (res) => res.questionId == this.question.id
                        );
                        if (testQuestion) {
                          testQuestion.score = res.data;
                        }
                      })
                      .catch((err) => console.log(err));
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "已取消关联",
                    });
                  });
              });
          }
          this.$message.success("更新成功!");
          if (!flag) {
            this.questionInfo();
            this.isEdit = false;
          } else {
            this.question = {
              id: null,
              testStructure: "",
              questionType: this.question.questionType,
              select: [
                {
                  select: "A",
                  content: "",
                },
                {
                  select: "B",
                  content: "",
                },
                {
                  select: "C",
                  content: "",
                },
                {
                  select: "D",
                  content: "",
                },
              ],
              answer: [],
              score: 1,
              type: "1",
              title: "",
              videoAnalyze: "",
              analyze: "",
              difficultyLevel: 1,
              parentId: this.parentQuestion.id,
              isOfficialQuestion: 0,
              officialQuestionSource: "",
              year: "",
              subjectId: parseInt(localStorage.getItem("question_subject")),
              options: {
                left: [
                  { index: 0, content: '' },
                  { index: 1, content: '' },
                  { index: 2, content: '' }
                ],
                right: [
                  { index: 0, content: '' },
                  { index: 1, content: '' },
                  { index: 2, content: '' }
                ]
              },
            };
            if (this.test.id) {
              this.question.testId = this.test.id;
              this.question.isOfficialQuestion = 1;
              this.question.officialQuestionSource = this.test.title;
              this.question.year = this.test.year;
            }
            this.knowledgePoints = [];
          }
        });
      },
      queryQuestionPoint() {
        queryQuestionPoint(this.question.id).then((res) => {
          this.knowledgePoints = res.data;
        });
      },
      addKnowledgePoint(index) {
        let point = this.$refs["point"].getCheckedNodes();
        if (!point) {
          this.$message({
            message: "请选择知识点",
            type: "warning",
            duration: 8000,
          });
          return;
        }
        point = point[0].data;
        point = {
          pointId: point.value,
          name: point.label,
        };
        knowledgePointExceedLimit(point.pointId).then((res) => {
          if (res.data) {
            this.$message({
              message:
                "警告哦，该知识点已关联10道或10道以上题目，建议一个知识点不要关联超过10道题目",
              type: "warning",
              duration: 8000,
            });
          }
        });
        if (this.knowledgePoints) {
          this.knowledgePoints.push(point);
        } else {
          this.knowledgePoints = [];
          this.knowledgePoints.push(point);
        }
        this.dialogFormVisible = false;

        // saveQuestionPoint(this.question.id, point).then(() => {
        //   this.queryQuestionPoint();
        //   this.dialogFormVisible = false;
        // });
      },
      updateSort(evt) {
        const changeTags = this.knowledgePoints[evt.newIndex];
        let sort;
        let beforeSort;
        let afterSort;
        if (evt.newIndex === 0) {
          beforeSort = this.knowledgePoints[evt.newIndex + 1].sort - 50;
        } else {
          beforeSort = this.knowledgePoints[evt.newIndex - 1].sort;
        }
        if (evt.newIndex === this.knowledgePoints.length - 1) {
          afterSort = this.knowledgePoints[evt.newIndex - 1].sort + 50;
        } else {
          afterSort = this.knowledgePoints[evt.newIndex + 1].sort;
        }
        sort =
          Math.floor(Math.random() * (afterSort - beforeSort + 1)) + beforeSort;
        // questionPointSort(this.question.id, changeTags.pointId, sort).then(
        //   (res) => {
        //     this.queryQuestionPoint();
        //   }
        // );
      },
      handleClose(tag) {
        this.knowledgePoints.splice(this.knowledgePoints.indexOf(tag), 1);
        // deleteQuestionPoint(this.question.id, tag.pointId).then((res) =>
        //   this.queryQuestionPoint()
        // );
      },
      customColorMethod(percentage) {
        if (percentage < 30) {
          return "#909399";
        } else if (percentage < 70) {
          return "#e6a23c";
        } else {
          return "#67c23a";
        }
      },
      handleAnswer() {
        if (this.question.type == 1) {
          this.question.answer = [this.question.answer[0]]
        }
        this.question.answer = this.question.answer.filter((item) =>
          this.question.select.find((s) => s.select === item)
        );
      },
      deleteVideo() {
        this.question.videoAnalyze = "";
        this.video = {
          sources: [],
          options: {
            autoplay: false,
            poster: "",
          },
        };
        this.videoUploadStatus = 0;
        this.percentage = 0;
      },
      upload(param) {
        const file = param.file;
        uploadAli(file, this);
      },
      removeItem(item) {
        this.question.select = this.question.select.filter((i) => i !== item);
      },
      addItem() {
        this.question.select.push({
          select: this.selectAnswer[this.question.select.length],
          content: "",
        });
      },
      getSubject() {
        getSubjectList().then((res) => {
          const transformData = (data) => {
            return data.map(item => ({
              value: item.id,
              label: item.name,
              children: item.children ? transformData(item.children) : undefined
            }));
          };
          this.subjectOptions = transformData(res.data);
        });

      },
      getArea() {
        getAreaList().then((res) => (this.areaList = this.getTreeData(res.data)));
      },
      removeOption(index, side) {
        this.question.options[side].splice(index, 1);
        // 更新剩余选项的index值
        this.question.options[side].forEach((option, idx) => {
          option.index = idx + 1;
        });
        // 更新连线关系，由于索引从1开始，需要处理对应关系
        if (side === 'left') {
          this.question.answer = this.question.answer.filter(conn => conn.left !== index + 1);
          // 更新大于当前索引的连接
          this.question.answer.forEach(conn => {
            if (conn.left > index + 1) conn.left--;
          });
        } else {
          this.question.answer = this.question.answer.filter(conn => conn.right !== index + 1);
          // 更新大于当前索引的连接
          this.question.answer.forEach(conn => {
            if (conn.right > index + 1) conn.right--;
          });
        }
      },
      getTreeData(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined;
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children);
          }
        }
        return data;
      },
      questionUp() {
        if (this.questionUpAndDown.up) {
          this.$router.push({
            path: "/questionInfo",
            query: {
              id: this.questionUpAndDown.up,
              activeName: this.$router.currentRoute.query.activeName,
            },
          });
        }
      },
      questionDown() {
        if (this.questionUpAndDown.down) {
          this.$router.push({
            path: "/questionInfo",
            query: {
              id: this.questionUpAndDown.down,
              activeName: this.$router.currentRoute.query.activeName,
            },
          });
        }
      },
      getQuestionUpAndDown() {
        if (this.question.id) {
          var activeName = this.$router.currentRoute.query.activeName;
          if (activeName) {
            questionUpAndDown(this.question.id, activeName).then((res) => {
              this.questionUpAndDown = res.data;
              if (this.questionUpAndDown.up) {
                this.questionUpDisabled = false;
              }
              if (this.questionUpAndDown.down) {
                this.questionDownDisabled = false;
              }
            });
          }
        }
      },
      isShowTestUpOrDown() {
        let existQuestion = false;
        for (let index = 0; index < this.testQuestionIdList.length; index++) {
          if (this.question.id == this.testQuestionIdList[index]) {
            existQuestion = true;
            break;
          }
        }
        return existQuestion;
      }
    },
  };
</script>
<style>
  .ai-analyze-content {
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #f9f9f9;
    margin-bottom: 15px;
  }
  
  .ai-analyze-content h5 {
    margin-top: 10px;
    margin-bottom: 5px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .ai-knowledge-content {
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #f9f9f9;
    margin-bottom: 15px;
  }
  
  .knowledge-item {
    margin-bottom: 10px;
    padding: 8px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fff;
  }
  
  .knowledge-name {
    font-weight: bold;
    color: #303133;
    margin-right: 10px;
  }
  
  .knowledge-confidence {
    color: #909399;
    font-size: 12px;
  }
  
  .line-question-container {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
  }

  .line-left-options,
  .line-right-options {
    width: 45%;
    padding: 15px;
    border: 2px dashed #dcdfe6;
    border-radius: 4px;
    min-height: 200px;
  }

  .line-option {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .line-option .el-input {
    margin-right: 10px;
    flex: 1;
  }

  .sticky {
    height: 80px;
    background-color: #f2f6fc;
  }

  .questionItem {
    margin-top: 5px;
  }

  .questionItem .el-card__body {
    padding: 12px;
  }

  .questionTitle p {
    margin: 0px;
  }

  .likeQuestion p {
    margin: 0px;
  }
</style>
<style scoped>
  .option-index {
    margin-right: 8px;
    font-weight: bold;
  }

  .connection-index {
    margin-right: 8px;
    font-weight: bold;
  }

  .line-option {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }

  .line-connection {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }

  .el-form-item {
    margin-bottom: 18px !important;
  }
</style>
</template>
